/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-common
*
* @File name : XSSFilter.java
*
* @Author : Administrator
*
* @Date : 2017年10月11日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年10月11日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.common.filter;
import java.io.IOException;  
import java.util.Enumeration;  
import java.util.Iterator;  
  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.log4j.Logger;
import org.springframework.core.annotation.Order; 

/**
 * @author Administrator
 * @date 2017年10月11日
 */
@Order(1)
@WebFilter(filterName = "Filter", urlPatterns = "/*")
public class XSSFilter implements Filter {

    public static final Logger logger  = Logger.getLogger(sun.reflect.Reflection.getCallerClass(1));

    // 需要过滤的post参数值字符(不需要空格 可能会对系统访问有影响，请注意删减关键字)
    private static String      postStr = "%20,script";
    // 需要过滤的post字符(可能会对系统访问有影响，请注意删减关键字)
    // private static String
    // sqlStr="<,>,and,exec,insert,select,%20,delete,update,count,*,%,chr,mid,master,truncate,char,like,declare,&,#,(,),/**/,=,script,\u0023,redirect:,xwork2";
    // --and , count
    private static String      sqlStr  = "exec,insert,select,%20,delete,update,chr,master,truncate,char,like,declare,#,/**/,script,\u0023,redirect:,xwork2";
    // 需要过滤的url字符(可能会对系统访问有影响，请注意删减关键字)
    private static String      urlStr  = "%20,%22,%27,<,>,master,truncate,char,script,java.lang.ProcessBuilder,java.lang.String,/etc/,\u0023,redirect:,xwork2,\u0073\u0063\u0072\u0069\u0070\u0074";

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
                                                                                              ServletException {
        request.setCharacterEncoding("utf-8");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        Enumeration names = req.getParameterNames();// 获取所有的表单参数
        String gotoUrl = req.getRequestURI(); // 获取访问的url
        String queryString = req.getQueryString();

        // 判断所有的参数名是否有非法字符
        while (names.hasMoreElements()) {
            String st = names.nextElement().toString();
            if (strInj(st, sqlStr) || strInj2(st, urlStr)) {
                req.getSession().setAttribute("msgStr", "请不要输入非法参数：" + req.getParameter(st) + " !");
//                res.sendRedirect("http://i-club.gmmc.com.cn/wx/views/ps.html");
                res.sendRedirect("http://localhost:80/wx/views/ps.html");
                return;
            }

        }

        // 判断所有的参数值是否有非法字符
        Iterator values = req.getParameterMap().values().iterator();// 获取所有的表单参数
        while (values.hasNext()) {
            String[] value = (String[]) values.next();
            for (int i = 0; i < value.length; i++) {
                if (strInj(value[i], sqlStr) || strInj2(value[i], postStr)) {
                    request.setAttribute("msgStr", "请不要输入非法参数：" + value[i] + " !");
//                    res.sendRedirect("http://i-club.gmmc.com.cn/wx/views/ps.html");
                    res.sendRedirect("http://localhost:80/wx/views/ps.html");
                    return;
                }

            }
        }

        // 判断访问的url中是否有非法参数
        if (queryString != null && strInj2(queryString, urlStr)) {
            req.getSession().setAttribute("msgStr", "请不要输入非法参数 !");
//            res.sendRedirect("http://i-club.gmmc.com.cn/wx/views/ps.html");
            res.sendRedirect("http://localhost:80/wx/views/ps.html");
            return;
        }

        chain.doFilter(request, response);
        System.out.println("Filter");
    }

    /**
     * 判断字符是否包含非法字符
     * 
     * @param str
     * @return
     */
    public static boolean strInj(String str, String standStr) {
        if (str == null || str.length() == 0) return false;
        String[] inj_stra = standStr.split(",");
        for (int i = 0; i < inj_stra.length; i++) {
            if (inj_stra[i].length() > 0 && str.toLowerCase().indexOf(inj_stra[i]) >= 0) {
                System.out.println(inj_stra[i]);
                return true;
            }
        }
        return false;
    }

    /**
     * 判断字符是否包含非法字符,没有空格
     * 
     * @param str
     * @return
     */
    public boolean strInj2(String str, String standStr) {
        if (str == null || str.length() == 0) return false;
        String[] inj_stra = standStr.split(",");
        for (int i = 0; i < inj_stra.length; i++) {
            if (inj_stra[i].length() > 0 && str.toLowerCase().indexOf(inj_stra[i]) >= 0) {
                return true;
            }
        }
        return false;
    }

    public void init(FilterConfig cfg) throws ServletException {

    }

//    public static void main(String[] args) {
//        XSSFilter sf = new XSSFilter();
//        String st = "<script text=\"javascript\">";
//        if (strInj(st, sqlStr)) {
//            System.out.println("=======:" + sqlStr.indexOf(st));
//        }
//        if (sf.strInj2(st, urlStr)) {
//            System.out.println("=======:" + urlStr.indexOf(st));
//        }
//    }
}
